package com.learning.rpc.rpc.protocol;

import com.learning.rpc.common.serialize.Serialization;
import com.learning.rpc.remoting.Client;
import com.learning.rpc.rpc.Invocation;
import com.learning.rpc.rpc.Invoker;
import com.learning.rpc.rpc.Response;
import com.learning.rpc.rpc.protocol.lrpc.handler.LrpcClientHandler;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ClientInvoker
 * Description: ClientInvoker
 * Date: 2022/5/10 22:45 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ClientInvoker implements Invoker {

    private Client client;
    private Serialization serialization;

    public ClientInvoker(Client client, Serialization serialization) {
        this.client = client;
        this.serialization = serialization;
    }

    @Override
    public Class getInterface() {
        return null;
    }

    @Override
    public Object invoke(Invocation invocation) throws Exception {
        // 1. 序列化 rpcInvocation -- 根据服务提供者的配置决定
        byte[] requestBody = serialization.serialize(invocation);
        // 2. 发起请求 -- invocation -- 协议数据包 -- 编码
        // 长连接传递数据
        this.client.getChannel().send(requestBody);
        // 3.另一个线程 接收响应?      // TODO ? 解码--> handler
        // 实现 等待结果的
        CompletableFuture completableFuture = LrpcClientHandler.waitResult(invocation.getId());
        // future.get 获取结果
        Object result = completableFuture.get(60, TimeUnit.SECONDS);
        Response response = (Response) result;
        if (response.getStatus() == 200) {
            return response.getContent();
        } else {
            throw new Exception("server error:" + response.getContent().toString());
        }
    }
}
